package com.ebus.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;

public class CharacterEncodingFilter implements Filter {

	private static final Logger log = Logger.getLogger(CharacterEncodingFilter.class);
			
	protected String encoding = null; // 要制定的编码，在web.xml中配置

	protected FilterConfig filterConfig = null;

	public void destroy() {
		this.encoding = null;
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (request.getCharacterEncoding() == null) {
			
			// 得到指定的编码名字
			String encoding = getEncoding(); 
			if (encoding != null)
				
				//设置request的编码
				request.setCharacterEncoding(encoding);
		}
		
		//有机会执行下一个filter
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		
		// 得到在web.xml中配置的编码
		this.encoding = filterConfig.getInitParameter("encoding"); 
		
		log.info("encoding="+encoding);
	}

	protected String getEncoding() {
		
		//得到指定的编码
		return (this.encoding);
	}

}
